﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using VOL.Core.EFDbContext;

namespace MyMes.Infrastructure
{
    /// <summary>
    /// 32432432
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        private readonly VOLContext db;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db"></param>
        public BaseRepository(VOLContext db)
        {
            this.db = db;
        }
        public async Task<int> AddAsync(T entity)
        {
            await db.Set<T>().AddAsync(entity);
            return await db.SaveChangesAsync();
        }

        public async Task<int> AddRange(IEnumerable<T> entities)
        {
            await db.Set<T>().AddRangeAsync(entities);
            return await db.SaveChangesAsync();
        }

        public async Task<int> DelAll(Expression<Func<T, bool>> expression)
        {
            var entitiesToDelete = await db.Set<T>().Where(expression).ToListAsync();
            db.Set<T>().RemoveRange(entitiesToDelete);
            var result = await db.SaveChangesAsync();
            return result;
        }

        public async Task<T> FindAsync(int id)
        {
            return await db.Set<T>().FindAsync(id);
        }
        public IQueryable<T> GetAll()
        {
            return db.Set<T>();
        }

        public IQueryable<T> GetAll(Expression<Func<T, bool>> expression)
        {
            return db.Set<T>().Where(expression);
        }

        public async Task<int> Remove(T entity)
        {
            db.Set<T>().RemoveRange(entity);
            return await db.SaveChangesAsync();
        }

        public async Task<int> RemoveRange(IEnumerable<T> entities)
        {
            db.Set<T>().RemoveRange(entities);
            return await db.SaveChangesAsync();
        }

        public async Task<int> UpdateAsync(T entity)
        {
            db.Set<T>().Update(entity);
            return await db.SaveChangesAsync();
        }

        public async Task<int> UpdRange(IEnumerable<T> entities)
        {
            db.Set<T>().UpdateRange(entities);
            return await db.SaveChangesAsync();
        }
    }
}
